<!--//This file is part of the store/retrieve project
//    (http://code.google.com/p/storeretrieve/).
//
//    Store/retrieve is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Store/retrieve is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with store/retrieve. If not, see <http://www.gnu.org/licenses/>.
//-->


<html>

<%@ page
	import="java.util.Properties,
		java.util.ArrayList,
		java.io.File,
		java.util.HashMap,
		java.io.FileInputStream,
		java.io.OutputStream,
		java.io.InputStream,
		de.devcity.storeretrieve.Tools"%>

<%@include file="includes/backend.jsp"%>

<%! 	
	Properties props;
	File file;
	ArrayList<File> containerFiles;
	Document doc;
%>

<%
	request.setCharacterEncoding("UTF-8");
	props = Tools.loadPropertiesByUser(getServletContext(), request.getRemoteUser()); 
	
	if(props == null) {
		response.sendRedirect("login.jsp");
	} else {
		HashMap<String, String> queryParms = new HashMap<String, String>();
		queryParms.put("Storage/Id", request.getParameter("id"));
		ArrayList<File> matches = query(props.getProperty("INTERNAL_REPO_PATH"), queryParms);
		if(matches.size() == 1) {
			file = new File(matches.get(0).getAbsolutePath() + "/" +
				new File(request.getParameter("file")).getName());
			if(file.exists()) {
				response.setContentType("application/octet-stream");
				if(file.length() < Integer.MAX_VALUE)
					 response.setContentLength((int)file.length());
				response.setHeader("content-disposition", "attachment; filename=" + file.getName());
				OutputStream os = response.getOutputStream();
				InputStream is = new FileInputStream(file);
				byte[] buf = new byte[32 * 1024];
    				int p = 0;
    				while((p=is.read(buf)) != -1) {
			        	os.write(buf, 0, p);
				}
			    	os.flush();
			    	is.close();
    				os.close();
    				return; 				
			} else {
				System.out.println(file.getAbsolutePath());
				throw new Exception("File not found.");
			}
		} else throw new Exception("Container unknown.");
	}
%>